#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
校准数据访问类完整使用示例
展示在实际项目中如何使用CalibrationDataReader类
"""

from calibration_data_reader import CalibrationDataReader
import json
import os


class AttenuatorCalibrationManager:
    """衰减器校准数据管理器
    
    实际项目中使用CalibrationDataReader的完整示例
    """
    
    def __init__(self, calibration_file="calibration_data.json"):
        """初始化校准管理器"""
        self.reader = CalibrationDataReader(calibration_file)
        self.tolerance = 0.5  # 默认容差 0.5dB
    
    def compensate_power_measurement(self, measured_power, attenuation_setting, frequency):
        """对功率测量进行校准补偿
        
        Args:
            measured_power: 原始测量功率值 (dBm)
            attenuation_setting: 衰减器设置值 (dB)
            frequency: 测量频率 (MHz)
            
        Returns:
            float: 补偿后的功率值 (dBm)
        """
        if not self.reader.is_data_available():
            print("⚠️ 警告: 没有校准数据，使用原始测量值")
            return measured_power
        
        # 获取实际衰减值（优先使用插值）
        actual_attenuation = self.reader.get_attenuation_with_interpolation(
            attenuation_setting, frequency
        )
        
        if actual_attenuation is None:
            print(f"⚠️ 警告: 无法获取{attenuation_setting}dB@{frequency}MHz的校准数据")
            return measured_power
        
        # 计算补偿量 = 实际衰减 - 设置衰减
        compensation = actual_attenuation - attenuation_setting
        
        # 应用补偿（从测量值中减去补偿量）
        compensated_power = measured_power - compensation
        
        print(f"📐 校准补偿:")
        print(f"   原始测量: {measured_power:.2f} dBm")
        print(f"   设置衰减: {attenuation_setting:.1f} dB")
        print(f"   实际衰减: {actual_attenuation:.3f} dB")
        print(f"   补偿量: {compensation:+.3f} dB")
        print(f"   补偿后: {compensated_power:.2f} dBm")
        
        return compensated_power
    
    def validate_attenuation_accuracy(self, setting, frequency):
        """验证衰减精度是否在容差范围内"""
        actual = self.reader.get_attenuation(setting, frequency)
        if actual is None:
            return False, f"没有校准数据"
        
        error = abs(actual - setting)
        is_valid = error <= self.tolerance
        
        return is_valid, f"误差: {error:.3f}dB ({'✅合格' if is_valid else '❌超差'})"
    
    def generate_calibration_report(self, output_file="calibration_report.txt"):
        """生成校准报告"""
        if not self.reader.is_data_available():
            print("❌ 无法生成报告: 没有校准数据")
            return False
        
        stats = self.reader.get_statistics()
        settings = self.reader.get_attenuation_settings()
        
        with open(output_file, 'w', encoding='utf-8') as f:
            f.write("="*60 + "\n")
            f.write("衰减器校准数据报告\n")
            f.write("="*60 + "\n\n")
            
            # 基本信息
            f.write("📊 基本信息:\n")
            f.write(f"   数据点总数: {stats['total_data_points']}\n")
            f.write(f"   衰减设置数: {stats['total_settings']}\n")
            f.write(f"   频率点数: {stats['total_frequencies']}\n")
            f.write(f"   频率范围: {stats['frequency_range']['min']:.1f} - {stats['frequency_range']['max']:.1f} MHz\n")
            f.write(f"   衰减范围: {stats['attenuation_range']['min']:.1f} - {stats['attenuation_range']['max']:.1f} dB\n\n")
            
            # 各设置下的统计
            f.write("📈 各衰减设置统计:\n")
            for setting in settings[:5]:  # 只显示前5个设置的详细信息
                setting_stats = self.reader.get_statistics(setting)
                if 'setting_specific' in setting_stats:\n                    ss = setting_stats['setting_specific']\n                    f.write(f"   {setting:.1f}dB: 频点数={ss['frequency_count']}, ")\n                    f.write(f"均值={ss['mean_attenuation']:.3f}dB, ")\n                    f.write(f"标准差={ss['std_attenuation']:.3f}dB\\n")\n            \n            if len(settings) > 5:\n                f.write(f"   ... 还有{len(settings)-5}个设置\\n")\n            \n            f.write("\\n")\n            \n            # 精度验证\n            f.write("🎯 精度验证 (容差±{:.1f}dB):\\n".format(self.tolerance))\n            total_points = 0\n            passed_points = 0\n            \n            for setting in settings:\n                frequencies = self.reader.get_frequencies(setting)\n                setting_passed = 0\n                \n                for frequency in frequencies:\n                    total_points += 1\n                    is_valid, msg = self.validate_attenuation_accuracy(setting, frequency)\n                    if is_valid:\n                        passed_points += 1\n                        setting_passed += 1\n                \n                pass_rate = (setting_passed / len(frequencies)) * 100 if frequencies else 0\n                f.write(f"   {setting:.1f}dB: {setting_passed}/{len(frequencies)} ({pass_rate:.1f}%)\\n")\n            \n            overall_pass_rate = (passed_points / total_points) * 100 if total_points > 0 else 0\n            f.write(f"\\n   总体合格率: {passed_points}/{total_points} ({overall_pass_rate:.1f}%)\\n")\n            \n            # 元数据\n            if stats['metadata']:\n                f.write("\\n📋 元数据:\\n")\n                for key, value in stats['metadata'].items():\n                    f.write(f"   {key}: {value}\\n")\n        \n        print(f"✅ 校准报告已生成: {output_file}")\n        return True\n    \n    def export_calibration_tables(self, base_filename="calibration_table"):\n        """导出校准表格"""\n        if not self.reader.is_data_available():\n            print("❌ 无法导出: 没有校准数据")\n            return False\n        \n        # 导出矩阵格式\n        matrix_file = f"{base_filename}_matrix.csv"\n        if self.reader.export_csv(matrix_file, "matrix"):\n            print(f"✅ 矩阵格式表格已导出: {matrix_file}")\n        \n        # 导出列表格式\n        list_file = f"{base_filename}_list.csv"\n        if self.reader.export_csv(list_file, "list"):\n            print(f"✅ 列表格式表格已导出: {list_file}")\n        \n        return True\n    \n    def find_best_calibration_point(self, target_setting, target_frequency):\n        """查找最佳校准点"""\n        closest = self.reader.find_closest_calibration_point(target_setting, target_frequency)\n        \n        if closest:\n            setting, frequency, attenuation = closest\n            setting_diff = abs(setting - target_setting)\n            freq_diff = abs(frequency - target_frequency)\n            \n            print(f"🎯 最佳校准点查找:")\n            print(f"   目标: {target_setting:.1f}dB @ {target_frequency:.1f}MHz")\n            print(f"   最佳: {setting:.1f}dB @ {frequency:.1f}MHz")\n            print(f"   差异: 设置±{setting_diff:.1f}dB, 频率±{freq_diff:.1f}MHz")\n            print(f"   实际衰减: {attenuation:.3f}dB")\n            \n            return closest\n        else:\n            print("❌ 未找到合适的校准点")\n            return None


def demo_real_world_usage():
    """演示实际使用场景"""\n    print("="*60)\n    print("🚀 校准数据访问类实际应用演示")\n    print("="*60)\n    \n    # 创建测试数据（模拟真实校准数据）\n    create_sample_calibration_data()\n    \n    # 创建校准管理器\n    manager = AttenuatorCalibrationManager("sample_calibration.json")\n    \n    print("\\n1. 功率测量补偿示例")\n    print("-" * 30)\n    \n    # 模拟功率测量场景\n    test_cases = [\n        {"power": -25.5, "setting": 30.0, "freq": 2400.0},\n        {"power": -45.2, "setting": 50.0, "freq": 5000.0},\n        {"power": -15.8, "setting": 20.0, "freq": 1000.0}\n    ]\n    \n    for case in test_cases:\n        compensated = manager.compensate_power_measurement(\n            case["power"], case["setting"], case["freq"]\n        )\n        print()\n    \n    print("\\n2. 精度验证示例")\n    print("-" * 30)\n    \n    test_points = [(10.0, 1000.0), (30.0, 2400.0), (50.0, 5000.0)]\n    for setting, freq in test_points:\n        is_valid, msg = manager.validate_attenuation_accuracy(setting, freq)\n        print(f"   {setting:.1f}dB @ {freq:.1f}MHz: {msg}")\n    \n    print("\\n3. 校准点查找示例")\n    print("-" * 30)\n    \n    # 查找非精确点的最佳校准点\n    manager.find_best_calibration_point(25.5, 3500.0)\n    \n    print("\\n4. 报告和导出示例")\n    print("-" * 30)\n    \n    # 生成报告\n    manager.generate_calibration_report()\n    \n    # 导出表格\n    manager.export_calibration_tables()\n    \n    print("\\n📋 生成的文件:")\n    for filename in ["calibration_report.txt", "calibration_table_matrix.csv", "calibration_table_list.csv"]:\n        if os.path.exists(filename):\n            print(f"   ✅ {filename}")\n    \n    print("\\n🎉 实际应用演示完成！")\n    \n    # 清理示例文件\n    cleanup_demo_files()


def create_sample_calibration_data():
    """创建示例校准数据"""\n    data = {\n        "metadata": {\n            "created_time": "2024-08-25 15:30:00",\n            "device_info": "示例衰减器 SN:12345",\n            "calibration_range": "100-6000MHz, 0-60dB",\n            "temperature": "23°C",\n            "humidity": "45%RH"\n        },\n        "calibration_data": {}\n    }\n    \n    # 生成示例数据：0-60dB，步进10dB\n    for setting in range(0, 61, 10):\n        setting_str = str(float(setting))\n        data["calibration_data"][setting_str] = {}\n        \n        # 频率点：1000, 2400, 5000MHz\n        for freq in [1000.0, 2400.0, 5000.0]:\n            freq_str = str(freq)\n            # 模拟真实衰减值（带小误差）\n            error = (freq / 10000) * 0.1 + setting * 0.002  # 模拟频率和设置相关的误差\n            actual_attenuation = setting + error\n            data["calibration_data"][setting_str][freq_str] = round(actual_attenuation, 3)\n    \n    with open("sample_calibration.json", 'w', encoding='utf-8') as f:\n        json.dump(data, f, indent=2, ensure_ascii=False)\n    \n    print("✅ 示例校准数据已创建")


def cleanup_demo_files():
    """清理演示文件"""\n    demo_files = [\n        "sample_calibration.json",\n        "calibration_report.txt", \n        "calibration_table_matrix.csv",\n        "calibration_table_list.csv"\n    ]\n    \n    print("\\n🗑️ 清理演示文件:")\n    for filename in demo_files:\n        if os.path.exists(filename):\n            os.remove(filename)\n            print(f"   已删除: {filename}")\n    print("   清理完成")


if __name__ == "__main__":\n    demo_real_world_usage()
